"use client"

import { useState } from "react"
import { useAdminStore } from "@/lib/store"
import { DataTable } from "@/components/common/data-table"
import { columns } from "./columns"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Plus } from "lucide-react"
import { RoleDialog } from "@/components/admin/role-dialog"
import { DeleteDialog } from "@/components/admin/delete-dialog"
import { Role } from "@/types/admin"

export default function RolesPage() {
  const { roles, deleteRole } = useAdminStore()
  
  // 对话框状态
  const [openAddEditDialog, setOpenAddEditDialog] = useState(false)
  const [selectedRole, setSelectedRole] = useState<Role | undefined>(undefined)
  const [openDeleteDialog, setOpenDeleteDialog] = useState(false)
  const [roleToDelete, setRoleToDelete] = useState<Role | undefined>(undefined)

  // 处理添加角色
  const handleAddRole = () => {
    setSelectedRole(undefined)
    setOpenAddEditDialog(true)
  }

  // 处理编辑角色
  const handleEditRole = (role: Role) => {
    setSelectedRole(role)
    setOpenAddEditDialog(true)
  }

  // 处理删除点击
  const handleDeleteClick = (role: Role) => {
    setRoleToDelete(role)
    setOpenDeleteDialog(true)
  }

  // 确认删除
  const handleConfirmDelete = () => {
    if (roleToDelete) {
      deleteRole(roleToDelete.id)
      setOpenDeleteDialog(false)
      setRoleToDelete(undefined)
    }
  }

  return (
    <div className="space-y-6">
      <Card className="card-shadow">
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-xl font-bold">角色管理</CardTitle>
          <Button 
            onClick={handleAddRole} 
            className="rounded-lg bg-primary hover:bg-primary/90"
          >
            <Plus className="mr-2 h-4 w-4" /> 新增角色
          </Button>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground mb-4">管理系统中的用户角色和权限。</p>
          <DataTable
            columns={columns({ onEdit: handleEditRole, onDelete: handleDeleteClick })}
            data={roles}
            pageSize={10}
            searchPlaceholder="搜索角色(支持角色名称、描述、权限等)"
          />
        </CardContent>
      </Card>

      <RoleDialog
        open={openAddEditDialog}
        onOpenChange={setOpenAddEditDialog}
        role={selectedRole}
      />

      <DeleteDialog
        open={openDeleteDialog}
        onOpenChange={setOpenDeleteDialog}
        onConfirm={handleConfirmDelete}
        title="删除角色"
        description={`确定要删除角色 "${roleToDelete?.name}" 吗？此操作无法撤销，且可能影响已分配该角色的用户。`}
      />
    </div>
  )
} 